package com.lenovo.smarttraffic.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.EnvironmentIndexInfo;
import com.lenovo.smarttraffic.database.dao.EnvironmentDatabase;
import com.lenovo.smarttraffic.ui.activity.environment.Co2Activity;
import com.lenovo.smarttraffic.ui.activity.environment.HumidityActivity;
import com.lenovo.smarttraffic.ui.activity.environment.IlluminationActivity;
import com.lenovo.smarttraffic.ui.activity.environment.PmActivity;
import com.lenovo.smarttraffic.ui.activity.environment.TemperatureActivity;
import com.lenovo.smarttraffic.ui.activity.environment.WayActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EnvironmentIndexActivity extends BaseActivity implements View.OnClickListener{

    private List<EnvironmentIndexInfo> list;
    private EnvironmentDatabase environmentDatabase;
    private SQLiteDatabase db;
    private final int TIMER_MSG = 0x001;    //定义headler消息代码
    private TextView tvTemperature;
    private TextView tvHumidity;
    private TextView tvIllumination;
    private TextView tvCo2;
    private TextView tvPm;
    private TextView tvWay;
    private int i = 0;
    private RelativeLayout relativeLayoutTem;
    private RelativeLayout relativeLayoutHum;
    private RelativeLayout relativeLayoutIll;
    private RelativeLayout relativeLayoutCo;
    private RelativeLayout relativeLayoutPm;
    private RelativeLayout relativeLayoutWay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //自定义标题栏
        initToolBar(findViewById(R.id.toolbar), true, getString(R.string.item6));

        tvTemperature = findViewById(R.id.environment_index_tv_temperature);
        tvHumidity = findViewById(R.id.environment_index_tv_humidity);
        tvIllumination = findViewById(R.id.environment_index_tv_illumination);
        tvCo2 = findViewById(R.id.environment_index_tv_co2);
        tvPm = findViewById(R.id.environment_index_tv_pm);
        tvWay = findViewById(R.id.environment_index_tv_way);
        relativeLayoutTem = findViewById(R.id.environment_index_relativelayout_temperature);
        relativeLayoutHum = findViewById(R.id.environment_index_relativelayout_humidity);
        relativeLayoutIll = findViewById(R.id.environment_index_relativelayout_illumination);
        relativeLayoutCo = findViewById(R.id.environment_index_relativelayout_co2);
        relativeLayoutPm = findViewById(R.id.environment_index_relativelayout_pm);
        relativeLayoutWay = findViewById(R.id.environment_index_relativelayout_way);
        relativeLayoutTem.setOnClickListener(this);
        relativeLayoutHum.setOnClickListener(this);
        relativeLayoutIll.setOnClickListener(this);
        relativeLayoutCo.setOnClickListener(this);
        relativeLayoutPm.setOnClickListener(this);
        relativeLayoutWay.setOnClickListener(this);

        //创建数据库
        environmentDatabase = new EnvironmentDatabase(this, "Environment.db", null, 1);
        environmentDatabase.getWritableDatabase();

        //给集合添加数据
        list = setList();

        //每隔3秒，更新一次数据
        handler.sendEmptyMessage(TIMER_MSG);



    }

    //使用headler消息延迟传递实现3秒数据更新
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIMER_MSG) {
                //获取数据并更新
                tvTemperature.setText(list.get(i).getTemperature()+"");
                tvHumidity.setText(list.get(i).getHumidity()+"");
                tvIllumination.setText(list.get(i).getIllumination()+"");
                tvCo2.setText(list.get(i).getCo2()+"");
                tvPm.setText(list.get(i).getPm()+"");
                tvWay.setText(list.get(i).getWay()+"");
                //判断数据是否超过阈值，超过的改变对应的控件颜色
                SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
                int tem = pref.getInt("tem", 35);
                int hum = pref.getInt("hum", 80);
                int ill = pref.getInt("ill", 800);
                int co = pref.getInt("co", 330);
                int pm = pref.getInt("pm", 300);
                int way = pref.getInt("way", 2);
                if (list.get(i).getTemperature() > tem) {
                    relativeLayoutTem.setBackgroundColor(Color.RED);
                } else {
                    relativeLayoutTem.setBackgroundResource(R.color.En_Green);
                }
                if (list.get(i).getHumidity() > hum) {
                    relativeLayoutHum.setBackgroundColor(Color.RED);
                } else {
                    relativeLayoutHum.setBackgroundResource(R.color.En_Green);
                }
                if (list.get(i).getIllumination() > ill) {
                    relativeLayoutIll.setBackgroundColor(Color.RED);
                } else {
                    relativeLayoutIll.setBackgroundResource(R.color.En_Green);
                }
                if (list.get(i).getCo2() > co) {
                    relativeLayoutCo.setBackgroundColor(Color.RED);
                } else {
                    relativeLayoutCo.setBackgroundResource(R.color.En_Green);
                }
                if (list.get(i).getPm() > pm) {
                    relativeLayoutPm.setBackgroundColor(Color.RED);
                } else {
                    relativeLayoutPm.setBackgroundResource(R.color.En_Green);
                }
                if (list.get(i).getWay() > way) {
                    relativeLayoutWay.setBackgroundColor(Color.RED);
                } else {
                    relativeLayoutWay.setBackgroundResource(R.color.En_Green);
                }
                //给数据库动态存数据
                setTargetData(list.get(i).getTemperature(), list.get(i).getHumidity(), list.get(i).getIllumination(),
                        list.get(i).getCo2(), list.get(i).getPm(), list.get(i).getWay());
                i++;
                if (i == list.size()) {
                    i = 0;
                }
                //消息延迟3秒发送
                handler.sendEmptyMessageDelayed(TIMER_MSG, 3000);
            }

        }
    };

    //给集合添加数据
    public List<EnvironmentIndexInfo> setList() {
        list = new ArrayList<>();
        list.add(new EnvironmentIndexInfo(32, 80, 567, 324, 254, 4));
        list.add(new EnvironmentIndexInfo(38, 72, 682, 288, 289, 1));
        list.add(new EnvironmentIndexInfo(28, 92, 856, 333, 325, 2));
        list.add(new EnvironmentIndexInfo(37, 76, 456, 256, 400, 1));
        list.add(new EnvironmentIndexInfo(26, 69, 565, 245, 125, 3));
        list.add(new EnvironmentIndexInfo(36, 82, 865, 355, 99, 5));
        list.add(new EnvironmentIndexInfo(29, 76, 952, 389, 65, 4));
        list.add(new EnvironmentIndexInfo(34, 85, 888, 315, 348, 2));
        list.add(new EnvironmentIndexInfo(37, 67, 756, 410, 450, 1));
        list.add(new EnvironmentIndexInfo(25, 75, 486, 240, 290, 1));
        return list;
    }

    //给Index表添加数据
    public void setTargetData(int temperature, int humidity, int illumination, int co2, int pm, int way) {
        int i = 0;
        //获取当前系统时间
        SimpleDateFormat df = new SimpleDateFormat("mm:ss"); //设置日期格式
        String date = df.format(new Date());
        db = environmentDatabase.getWritableDatabase();
        ContentValues values = new ContentValues();
        //开始组装第一条数据
        values.put("temperature", temperature);
        values.put("humidity", humidity);
        values.put("illumination", illumination);
        values.put("co2", co2);
        values.put("pm", pm);
        values.put("way", way);
        values.put("time", date);
        db.insert("Target", null, values);
        values.clear();
        if (db.rawQuery("select * from Target", null).getCount() > 20) {
            //查询第一个主键id
            Cursor cursor = db.query("Target", null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
              i = cursor.getInt(cursor.getColumnIndex("id"));
            }
            cursor.close();
            db.delete("Target", "id = "+i, null);
        }

    }

    //点击传感器事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.environment_index_relativelayout_temperature:
                Intent intent = new Intent(getApplicationContext(), TemperatureActivity.class);
                startActivity(intent);
                break;
            case R.id.environment_index_relativelayout_humidity:
                Intent intent1 = new Intent(getApplicationContext(), HumidityActivity.class);
                startActivity(intent1);
                break;
            case R.id.environment_index_relativelayout_illumination:
                Intent intent2 = new Intent(getApplicationContext(), IlluminationActivity.class);
                startActivity(intent2);
                break;
            case R.id.environment_index_relativelayout_co2:
                Intent intent3 = new Intent(getApplicationContext(), Co2Activity.class);
                startActivity(intent3);
                break;
            case R.id.environment_index_relativelayout_pm:
                Intent inten4 = new Intent(getApplicationContext(), PmActivity.class);
                startActivity(inten4);
                break;
            case R.id.environment_index_relativelayout_way:
                Intent inten5 = new Intent(getApplicationContext(), WayActivity.class);
                startActivity(inten5);
                break;
                default:
                    break;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_environment_index;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

}
